package com.lagou.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;

/**
 * 客户端
 */
public class NIOClient {

    public static void main(String[] args) throws Exception {
        // 创建线程池
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2    , 10, 60, TimeUnit.SECONDS,
                                                                new ArrayBlockingQueue<Runnable>(1),
                                                                new ThreadPoolExecutor.DiscardOldestPolicy());
        // 发起并发调用
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            threadPool.execute(() -> {
                //可以和客户端通讯
                try {
                    handle(finalI);
                } catch (IOException e) {
                }
            });
        }
        // 监控线程池
        while (true) {
            if (threadPool.getActiveCount() <= 0) {
                threadPool.shutdown();
                System.out.println("关闭线程池....");
                break;
            }
            Thread.sleep(1000);
        }
        if (!threadPool.isTerminated()) {
            System.out.println("强制关闭线程池....");
            threadPool.shutdownNow();
        }
    }

    private static void handle(int i) throws IOException {
        //1.打开通道
        SocketChannel socketChannel = SocketChannel.open();
        //2.设置连接IP和端口号
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
        //3.写出数据
        socketChannel.write(ByteBuffer.wrap(("我是" + i + "号员工,老板, 该还钱拉!").getBytes(StandardCharsets.UTF_8)));
        //4.读取服务器写回的数据
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        int read=socketChannel.read(readBuffer);
        System.out.println("服务端消息:" + new String(readBuffer.array(), 0, read, StandardCharsets.UTF_8));
        //5.释放资源
        socketChannel.close();
    }
}
